import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
//链接超时监测消息通道key
const link_timeout_message = "timeout"
//链接超时时间（毫秒）
const timeout = 30000
//链接成功消息通道key
const link_success_key = 'message'
//列表刷新间隔(秒)
const newlist_time = 30

//连接成功计时器
let time_linkval = null
//连接超时定时器实例
let link_timeout = null

let link_timeval = null

//失败消息通道监听开启状态
let fail_msg_watch = false


let padding_msg = null


export const useStore = defineStore('usePinia', {
    state: () => {
        return {
            link_state: 'false', //连接状态
            link_timeval: null,  //刷新定时器实例
            link_time: 0,    //连接成功计时
            list: [],    //连接成员列表
            tokenlist: localStorage.getItem('list') ? JSON.parse(localStorage.getItem('list')) : [],
            token: ''
        }
    },
    actions: {
        async getStatus(){
            let state=await window.go.main.TunStatus.Get_tun()
            
            if(state=='ok'){
                getlist()
            }else{
                this.link_state='false'
            }
        },
        getlist() {
            if (this.link_state == 'false') {
                return
            }
            window.go.main.TunStatus.GetStatus().then(res => {
                // console.log(res)
                if (res.length == 1 && ((res[0].msg&&res[0].msg!=="")||res[0].ip=='')) {
                    window.go.main.Todos.SetErrLogs("获取用户信息列表失败!")
                    this.link_timeout_fail()
                    setTimeout(() => {
                        this.getlist()
                    }, 1000)
                } else {
                    if (this.link_state == 'padding') {
                        this.link_success()
                    }
                    this.list = res
                    res.map(item => {
                        window.go.main.Todos.SetSuccessLogs("获取用户信息列表成功!,用户列表:"+JSON.stringify(res))
                        if (item.name.indexOf("本机") !== -1) {
                            let arr = item.name.split("(本机)")
                            if (this.tokenlist.filter(item => item.token == this.token).length == 0) {
                                let obj = {
                                    token: this.token,
                                    name: arr[0]
                                }
                                this.addToken(obj)
                            }
                        }
                    })
                }
            })
        },
        //连接成功
        link_success() {
            if (link_timeout !== null) {
                clearTimeout(link_timeout)
            }
            ElMessage.success("链接成功")
            this.link_state = 'true'
            if (time_linkval !== null) {
                clearInterval(time_linkval)
            }
            this.list_timeval()
            time_linkval = setInterval(() => {
                this.link_time++
            }, 1000)
            if (fail_msg_watch == false) {
                fail_msg_watch = true
                window.runtime.EventsOnMultiple(link_timeout_message, (msg) => {
                    window.go.main.Todos.SetLogs(msg)
                    // console.log(link_timeout_message,":  ",msg)
                    // this.link_timeout_fail()
                    this.getlist()
                }, -1)
            }
        },
        async link_start() {
            await this.getStatus()
            if (this.link_state == "padding") {
                return
            }
            if (this.link_state !== 'padding') {
                ElMessage.info("正在建立连接")
            }
            this.link_state = "padding"
            window.go.main.Todos.Run()
            window.runtime.EventsOnMultiple(link_success_key, (msg) => {
                // console.log("msg:", msg)
                if (msg.indexOf("连接成功") !== -1 || msg.indexOf("p2p socket 连接服务成功") !== -1) {
                    if (this.link_state == "padding") {
                        this.getlist()
                    }
                }
            }, -1)
        },
        //连接失败
        async link_fail() {
            this.token = ''
            ElMessage.error("与服务器已断开连接")
            this.link_state = 'false'
            fail_msg_watch = false
            await window.go.main.TunStatus.Tun_close()
            this.link_time = 0
            if (time_linkval !== null) {
                clearInterval(time_linkval)
            }
            this.list = []
            //关闭链接失败消息通道监听
            window.runtime.EventsOff(link_timeout_message)
            window.runtime.EventsOff(link_success_key)
        },
        //连接超时计算
        link_timeout_fail() {
            if (this.link_state !== 'padding') {
                if (this.link_state == 'false') {
                    ElMessage.info("正在连接中")
                } else {
                    // ElMessage.info("连接断开,正在重连..")
                }
                this.link_state = 'padding'
            } else {
                return
            }
            if (link_timeout !== null) {
                clearTimeout(link_timeout)
            }
            link_timeout = setTimeout(() => {
                ElMessage.error("连接已断开")
                this.link_fail()
            }, newlist_time * 1000)
        },
        //列表刷新
        list_timeval() {
            if (this.link_timeval !== null) {
                this.getlist()
                clearInterval(this.link_timeval)
            }
            this.link_timeval = setInterval(() => {
                this.getlist()
            }, newlist_time * 1000)
        },
        addToken({ token, name }) {
            let arr = this.tokenlist.filter(item => item.token == token)
            if (arr.length > 0) {
                return
            }
            this.tokenlist.unshift({ token, name })
            if(this.tokenlist.length>5){
                this.tokenlist=this.tokenlist.splice(0,5)
            }
            localStorage.setItem("list", JSON.stringify(this.tokenlist))
        },
        removeToken(token) {
            let index=this.tokenlist.findIndex(item => item.token == token)
            if (index == -1) {
                ElMessage.info("不存在此token")
                return
            }
            this.tokenlist.splice(index, 1)
            localStorage.setItem("list", JSON.stringify(this.tokenlist))
            ElMessage.success("删除成功")
        }
    }
})